package day9.callable_demo;

import java.util.concurrent.*;
/**
 * callable线
 *   发布任务，委托其它线程计算并同步结果
 *      1.做好数据的共享
 *      2.主线程发布任务之后，需要等待子线程完成(同步)
 *      3.子线程要把数据给回主线程(写共享数据->线程安全)
 */
public class Main {
    static class FibCalc implements Callable<Long> {
        private final int n;

        FibCalc(int n) {
            this.n = n;
        }

        private long fib(int n) {
            if (n == 0 || n == 1) {
                return 1;
            }

            return fib(n - 1) + fib(n - 2);
        }

        @Override
        public Long call() throws Exception {
            return fib(n);
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService service = Executors.newSingleThreadExecutor();
        FibCalc task = new FibCalc(40);

        Future<Long> future = service.submit(task);

        Long r = future.get();  // 这一步实际上是在等任务计算完成，所以，时间可能需要很久
        System.out.println(r);
    }
}
